<?php

namespace frontend\modules\Api\controllers;

use common\models\Material;
use common\models\TallyProject;
use common\services\TallyMaterialServices;
use common\services\UploadLocalServices;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Yii;
use yii\base\DynamicModel;
use yii\base\ExitException;
use yii\base\InvalidConfigException;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;

class MaterialController extends ApiController
{
    /**
     * @return array
     * 引入行为验证 过滤授权
     */
    public function behaviors()
    {
        $config = [
            'access' => [
                'class' => AccessControl::className(),
                'denyCallback' => function($rule, $action){
                    return self::failureResponse(100001, '请先登录!',[]);
                },
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ]
                ]
            ],
        ];
        return ArrayHelper::merge(parent::behaviors(), $config);
    }

    public function actionListsAll(){
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $list = TallyMaterialServices::getListAll([
            'tally_id'=>$tallyId
        ]);
        return  self::successResponse($list);
    }


    /**
     * @throws
     * 项目列表
     */
    public function actionLists()
    {
        $condition = Yii::$app->request->get(); // type 等参数
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId,'read');

        $list = TallyMaterialServices::getList($condition);
        $retData['data'] = [];
        $retData['pageInfo'] = [];
        // 遍历拼装附件数据
        foreach ($list['data'] as $lv) {
            $tmpData = $lv->toArray();
            $retData['data'][] = $tmpData;
        }
        $retData['pageInfo'] = $list['pageInfo'];
        return self::successResponse($retData);
    }


    /**
     * @throws ExitException
     * @throws InvalidConfigException
     */
    public function actionAdd(){
        $form = DynamicModel::validateData([
            'title' => Yii::$app->getRequest()->post('title'),
            'spec' => Yii::$app->getRequest()->post('spec'),
            'uid'   => $this->_user['id'],
            'tally_id'   => Yii::$app->getRequest()->post('tally_id'),
            'price'  => Yii::$app->getRequest()->post('price',1),
            'memo'  => Yii::$app->getRequest()->post('memo',''),
        ],[
            [['title'], 'required'],
            ['title', 'filter', 'filter' => 'trim'],
            ['price', 'number'],
        ]);
        if ($form->hasErrors()) {
            return self::failureResponse(500,current($form->getFirstErrors()));
        }

        $result = TallyMaterialServices::add(ArrayHelper::toArray($form));
        if($result){
            return self::successResponse(['id'=>$result]);
        }else{
            return self::failureResponse(500,'新增失败.'.TallyProjectService::getError());
        }
    }


    /**
     * @throws ExitException
     * @throws Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     */
    public function actionImportData(){
        $tally_id = Yii::$app->getRequest()->post('tally_id');
        $fileRes = UploadLocalServices::uploadLocalFu();
        if($fileRes['code'] != 0){
            return  self::failureResponse(500,$fileRes['msg']);
        }
        $filePath = $fileRes['data']['path'];
        $spreadsheet = IOFactory::load($filePath);
        $data = $spreadsheet->getSheet(0)->toArray();
        $exitDatas = Material::find()->where([
            'tally_id'=>$tally_id
        ])->select('title')->asArray()->all();
        $exitDatas = array_column($exitDatas,'title');
        $in_data = [];
        foreach ($data as $key=>$value){
            if($key > 0 && !in_array($value[0],$exitDatas)){
                $in_data[] = [
                    'tally_id'=>$tally_id,
                    'title'=>$value[0],
                    'spec'=>$value[1],
                    'memo'=>$value[2],
                    'uid'=>$this->_user['id']
                ];
                $exitDatas[] = $value[0];
            }
        }
        $res = Yii::$app->db->createCommand()->batchInsert('material', ['tally_id', 'title','spec','memo','uid'], $in_data)->execute();
        if($res > 0){
            return self::successResponse();
        }
        return self::failureResponse(500,'导入失败');
    }


    public function actionEdit(){
        $form = DynamicModel::validateData([
            'id'    => Yii::$app->getRequest()->post('id'),
            'title' => Yii::$app->getRequest()->post('title'),
            'spec' => Yii::$app->getRequest()->post('spec'),
            'uid'   => $this->_user['id'],
            'tally_id'   => Yii::$app->getRequest()->post('tally_id'),
            'price'  => Yii::$app->getRequest()->post('price',1),
            'memo'  => Yii::$app->getRequest()->post('memo',''),
        ],[
            [['title'], 'required'],
            ['title', 'filter', 'filter' => 'trim'],
            ['price', 'number'],
        ]);
        if ($form->hasErrors()) {
            return self::failureResponse(500,current($form->getFirstErrors()));
        }
        $result = TallyMaterialServices::update([
            'id'=>$form->id
        ],ArrayHelper::toArray($form));
        if($result){
            return self::successResponse(['id'=>$result]);
        }else{
            return self::failureResponse(500,'新增失败.'.TallyProjectService::getError());
        }
    }







    /**
     * @throws
     * 删除成员
     */
    public function actionDel()
    {
        $id = Yii::$app->getRequest()->post('id');
        if(!$id){
            return self::failureResponse(500,'账户Id不能为空');
        }
        // 检查对账本的操作权限
        $tallyId = Yii::$app->getRequest()->post('tally_id');
        $this->checkRolePermission($this->_user['id'],$tallyId,'write');
        $result = TallyMaterialServices::delete([
            'id'    => $id,
            'tally_id' => $tallyId
        ]);
        if($result){
            return self::successResponse();
        }else{
            return self::failureResponse(500,'删除失败.'.TallyMemberService::getError());
        }
    }
}